<?php
/**
 * Created by PhpStorm.
 * User: jocky
 * Date: 2017/7/19
 * Time: 下午3:35
 */

namespace common\models;

use common\models\ar\SysConfig;
use common\models\ar\User;
use common\models\ar\UserTrade;
use common\models\ar\UserBrokers;
class UserDao
{
    /**
     * 根据用户ID获取用户对象（代理或客户）
     *
     * @param $uid
     * @return mixed
     */
    public static function getUserObj($uid)
    {
        $sysConfig = SysConfig::find()->where(['key' => 'uid_separate_point'])->one();
        if ($uid >= $sysConfig->value) {
            $obj = User::findOne($uid);
        } else {
            $obj = UserTrade::findOne($uid);
        }
        return $obj;
    }

    /**
     * 三张用户表中检测该账号是否已存在
     *
     * @param $account
     * @return bool
     */
    public static function checkUserIsExist($account)
    {
        if (User::find()->where(['account' => $account])->count()) {
            return true;
        }

        if (UserTrade::find()->where(['account' => $account])->count()) {
            return true;
        }

        return false;
    }

    /**
     * 获取代理记录
     * @param int $uid 查询账户
     * @param int $start 注册起始日期
     * @param int $end 注册结束日期
     * @param int $pageNo
     * @param int $pageSize
     * @param array $orderByArr 根据字段排序，如['username'=>'asc']
     * @return array
     */
    public static function agentLists(
        $uid = -1,
        $start = 0,
        $end = 0,
        $pageNo = 1,
        $pageSize = 15,
        $orderByArr = ['id' => 'desc']
    ) {
        $db = \Yii::$app->db;

        $sql_count = "SELECT  COUNT(1) count FROM `user_brokers` a ";
        $sql_lists = "SELECT a.* FROM  `user_brokers` a ";
        $sql_where = '';
        $sql_join = "";
        $sql_orderBy = '';
        $sql_limit = " LIMIT " . ($pageNo - 1) * $pageSize . "," . $pageSize;
        $bind_arr = [];
        $tmpWhere = [];
        if(\Yii::$app->user->identity->loginName!='admin'){
          //upperLevelId  上级代理商Id
            $upperLevelIds=UserBrokers::findOne(['loginName'=>\Yii::$app->user->identity->loginName]);
            $tmpWhere[]='a. `upperLevelId`= :upperLevelId';
            $bind_arr[':upperLevelId'] = $upperLevelIds['id'];
        }
        if ($uid != -1) {
            $tmpWhere[] = 'a.`userID` = :uid';
            $bind_arr[':uid'] = $uid;
        }

        if ($start != 0) {
            $tmpWhere[] = 'a.`create_time` =>= :time_start';
            $bind_arr[':time_start'] = $start;
        }

        if ($end != 0) {
            //结束日期包含当天
            $tmpWhere[] = 'a.`create_time` < :time_end';
            $bind_arr[':time_end'] = $end + 24 * 3600;
        }
        if (!empty($tmpWhere)) {
            $sql_where = 'WHERE ' . implode(' AND ', $tmpWhere);
        }

        $total = $db->createCommand($sql_count . $sql_where, $bind_arr)->queryScalar();
        $tmpOrderByArr = [];
        if (!empty($orderByArr)) {
            $sql_orderBy = " ORDER BY ";
            foreach ($orderByArr as $k => $v) {
                $tmpOrderByArr[] = "a.`" . $k . "` " . $v;
            }
            $sql_orderBy .= implode($tmpOrderByArr, ' , ');
        }
//        var_dump($sql_lists);
//        var_dump($sql_join);
//        var_dump($sql_where);
//        var_dump($sql_orderBy);
//        var_dump($sql_limit);
//        var_dump($bind_arr);
//        exit();
        $lists = $db->createCommand(
            $sql_lists . $sql_where . $sql_join . $sql_orderBy . $sql_limit,
            $bind_arr
        )->queryAll();

        return [
            'total' => $total,
            'lists' => $lists
        ];
    }

    /**
     * 获取交易客户记录
     *
     * @param int $regType 注册来源，-1所有，1上级代理注册，2推荐码网页注册
     * @param int $pid 父级用户
     * @param int $pLevel 父级账户等级
     * @param int $uid 查询账户
     * @param int $start 注册起始日期
     * @param int $end 注册结束日期
     * @param int $pageNo
     * @param int $pageSize
     * @param array $orderByArr 根据字段排序，如['username'=>'asc']
     * @return array
     */
    public static function traderLists(
        $regType = -1,
        $pid = -1,
        $pLevel = -1,
        $uid = -1,
        $start = 0,
        $end = 0,
        $pageNo = 1,
        $pageSize = 15,
        $orderByArr = ['userID' => 'desc']
    ) {
        $Uids = \Yii::$app->user->identity->id;
        $Uids=UserBrokers::findOne(['id'=>$Uids]);
        $db = \Yii::$app->db;
        $sql_count = "SELECT  COUNT(1) count FROM `user` a ";
        $sql_lists = "SELECT a.*,b.`status` realNameStatus FROM `user` a LEFT JOIN `real_name` b ON a.`userID` = b.`userID`";
        $sql_where = '';
//        $sql_join = '&& a.level=2';
         $sql_join ="";
        $sql_orderBy = '';
        $sql_limit = " LIMIT " . ($pageNo - 1) * $pageSize . "," . $pageSize;
        $bind_arr = [];

        $tmpWhere = [];

        if ($regType != -1) {
            $tmpWhere[] = 'a.`register_type` = :register_type';
            $bind_arr[':register_type'] = $regType;
        }
        if ($pid != -1) {
            if ($Uids['upperLevelId']!=0 && $Uids['loginName']!='admin'){

                $tmpWhere[] = 'a.`agentID`= :agentID';
                $bind_arr[':agentID'] = $Uids['id'];
            }
        }

        if ($uid != -1) {
            $tmpWhere[] = 'a.`userID` = :uid';
            $bind_arr[':uid'] = $uid;
        }

        if ($start != 0) {
            $tmpWhere[] = 'a.`create_time` =>= :time_start';
            $bind_arr[':time_start'] = $start;
        }

        if ($end != 0) {
            //结束日期包含当天
            $tmpWhere[] = 'a.`create_time` < :time_end';
            $bind_arr[':time_end'] = $end + 24 * 3600;
        }
        if (!empty($tmpWhere)) {
            $sql_where = 'WHERE ' . implode(' AND ', $tmpWhere);
        }
        $total = $db->createCommand($sql_count . $sql_where, $bind_arr)->queryScalar();
        $tmpOrderByArr = [];
        if (!empty($orderByArr)) {
            $sql_orderBy = " ORDER BY ";
            foreach ($orderByArr as $k => $v) {
                $tmpOrderByArr[] = "a.`" . $k . "` " . $v;
            }
            $sql_orderBy .= implode($tmpOrderByArr, ' , ');
        }
//        var_dump($sql_lists);
//        var_dump($sql_where);
//        var_dump($sql_join);
//        var_dump($sql_orderBy);
//        var_dump($sql_limit);
//        var_dump($bind_arr);
//        exit();
        $tmp = $db->createCommand(
            $sql_lists  . $sql_where. $sql_join . $sql_orderBy . $sql_limit,
            $bind_arr
        )->queryAll();
        $lists = [];
        $uidArr = [];
        $loginIDArr = [];
        $map = [];
        foreach ($tmp as $v) {
            $uidArr[] = $v['userID'];
            $loginIDArr[] = $v['loginName'];
            $map[$v['loginName']] = $v['userID'];
            $lists['lists_' . $v['userID']] = $v;
        }
        // var_dump($total);
        // var_dump($lists);
        // exit();
        return [
            'total' => $total,
            'lists' => $lists
        ];
    }


    /**
     * 创建资管中的交易客户
     *
     * @param int $uidOperate
     * @param $attr
     * @param $time
     * @param int $uid 创建的交易账户UID
     * @param $ip
     * @param $ua
     * @return bool
     */
    public static function addTrader(
        $uidOperate,
        &$uid,
        $attr
    ) {

        $bool = self::addAccount($uidOperate, $uid,$attr, $msg);
        return $bool;
        exit();
        if ($bool) {
            $bool = self::addTraderInTradeSystem($uid, $attr, $time, $msg);

            //创建账户状态改变
            $obj = UserTrade::findOne($uid);
            $obj->status = $bool ? 1 : 2;
            $obj->last_fail_msg = $msg;
            $obj->save();
        }

        return $bool;
    }

    /**
     * 资管系统中创建代理或交易账号
     *
     * @param $uidOperate
     * @param $uid
     * @param int $userType 1代理，2客户
     * @param $attr
     * @param $time
     * @param $msg
     * @param $ip
     * @param $ua
     *
     * @return bool
     */
    public static function addAccount(
        $uidOperate,
        &$uid,
        $attr,
        &$msg
    ) {
        $table ="`user`";
        $db = \Yii::$app->db;
        $transaction = $db->beginTransaction();
        try {
            //插入记录
            $sql = "INSERT INTO $table (" . implode(',', array_keys($attr)) . ") VALUES ";
            $tmp_k = [];
            $tmp_v = [];
            foreach ($attr as $k => $v) {
                $tmp_k[] = ':' . $k;
                $tmp_v[':' . $k] = $v;
            }
            $sql .= "(" . implode(',', $tmp_k) . ")";
            print_r($sql);
            var_dump($tmp_v);
            exit();
            $db->createCommand($sql,$tmp_v)->execute();
            $uid = $db->getLastInsertID();
            var_dump($uid);
            exit();
            if ($uidOperate == 0) {
                $uidOperate = $uid;
            }
            $transaction->commit();
            $bool = true;
        } catch (\Exception $e) {
            $msg = $e->getMessage();
            $uid = 0;
            $transaction->rollBack();
            $bool = false;
        }

        return $bool;
    }

    /**
     * 在交易系统中创建交易用户记录
     *
     * @param $uid
     * @param $attr
     * @param $time
     * @param string $msg 创建账户反馈信息
     * @return bool
     */
    public static function addTraderInTradeSystem($uid, $attr, $time, &$msg)
    {
        $date = date("Y-m-d H:i:s", $time);
        $db = \Yii::$app->db_options;
        $transaction = $db->beginTransaction();
        try {
            //用户表
            $sql = "INSERT INTO `user` (
                      `userID`, 
                      `loginName`,
                      `loginPsw`,
                      `accountName`,
                      `userType`,
                      `cellPhone`,
                      `RegisterDate`,
                      `line_waring`,
                      `line_LimitOpen`,
                      `line_ForceClose`,
                      `reserveMultiple`,
                      `limit_openorder`,
                      `confir_settlement_time`,
                      `money_psw`,
                      `auto_forceClose`,
                      `agentID`,
                      `Accountid`,
                      `commissionID`,
                    )  VALUES (
                      :uid,
                      :loginName,
                      :pwd,
                      :accountName,
                      :userType,
                      :cellphone,
                      :RegisterDate,
                      :line_warning,
                      :line_LimitOpen,
                      :line_ForceClose,
                      :reserveMultiple,
                      :limit_openorder,
                      :confir_settlement_time,
                      :money_psw,
                      :auto_forceClose,
                      :agentID,
                      :Accountid,
                      :commissionID,
              
                    ) 
            ";
            $bind = [
                ':uid' => $uid,
                ':loginName' => $attr['clientSN'],
                ':pwd' => $attr['password_plain'],
                ':accountName' => $attr['alias'],
                ':userType' => 1001,
                ':cellphone' => isset($attr['cellphone']) ? $attr['cellphone'] : ' ',
                ':RegisterDate' => $date,
                ':line_warning' => $attr['line_warning'] * 100,
                ':line_LimitOpen' => $attr['line_open'] * 100,
                ':line_ForceClose' => $attr['line_force_close'] * 100,
                ':reserveMultiple' => '1', // 当hedgeStrategy为反向跟单时，该值对应的跟单倍数
                ':limit_openorder' => $attr['limit_open'],//0不限制，1限制开仓
                ':confir_settlement_time' => $date,
                ':money_psw' => $attr['password'],
                ':auto_forceClose' => 1, // 达到强平线则自动进行强制平仓
                ':agentID' => $attr['pid'],
                ':Accountid' => 19,
                ':commissionID' => $attr['template_id'],
               
            ];
            $db->createCommand($sql, $bind)->execute();

            //资金表
            $sql = "INSERT INTO `user_money` (
                      `userID`, 
                      `totalMoney`,
                      `userDeposit`,
                      `equip`
                    ) VALUES  (
                      :uid,
                      :totalMoney,
                      :userDeposit,
                      :equip
                    )
            ";
            $db->createCommand($sql, [
                ':uid' => $uid,
                ':totalMoney' => 0,
                ':userDeposit' => 0,
                ':equip' => 0
            ])->execute();

            //change_cache通知表
            $sql = "INSERT INTO `change_cache` (`userid`, `change_type`) values (:uid, :type)";
            $db->createCommand($sql, [':uid' => $uid, ':type' => 1])->execute();

            $msg = '';
            $transaction->commit();
            $bool = true;
        } catch (\Exception $e) {
            $msg = $e->getMessage();
            $transaction->rollBack();
            $bool = false;
        }

        return $bool;
    }

    /**
     * 创建直属层级
     *
     * @param $uidOperate
     * @param $password
     * @param $time
     * @param $direction_links
     * @param $ip
     * @param $ua
     *
     * @return bool
     */
    public static function createDirectLinks(
        $uidOperate,
        $password,
        $time,
        $direction_links = '',
        $ip = '',
        $ua = ''
    ) {
        $pObj = User::findOne($uidOperate);

        $levelInfo = Common::getLevelsInfo($pObj->level);
        $clientSN = Common::getClientSN($levelInfo['cid']);
        $passwordSalt = mt_rand(100000, 999999);
        if (!$levelInfo['is_last']) {
            $attr['account'] = $clientSN;
            $attr['clientSN'] = $clientSN;
            $attr['alias'] = $pObj->alias;
            $attr['level'] = $levelInfo['cid'];
            $attr['password'] = md5(md5($password) . $passwordSalt);
            $attr['password_salt'] = $passwordSalt;
            $attr['create_time'] = $time;
            $attr['cellphone'] = $pObj->cellphone;
            $attr['pid'] = $uidOperate;
            $attr['recommend_code'] = Common::genRecommendCode();
            $attr['register_type'] = 1;
            $attr['uid_links'] = $pObj->uid_links;
            $attr['template_id'] = 0;

            //所属的各级代理
            $sql = "SELECT `uid`,`level` FROM `user` WHERE `uid` IN (" . $pObj->uid_links . ")";
            $tmp = User::findBySql($sql)->orderBy('level asc')->all();
            foreach ($tmp as $v) {
                $attr['uid_level_' . $v['level']] = $v['uid'];
            }

            $bool = self::addAccount($uidOperate, $uid, 1, $attr, $time, $msg, $ip, $ua);
            if (!$bool) {
                return false;
            }

            if ($direction_links == '') {
                $direction_links .= $uidOperate;
            }
            $direction_links .= "," . $uid;

            return self::createDirectLinks($uid, $password, $time, $direction_links, $ip, $ua);
        } else {
            //创建交易账户
            $sysConfig = Common::sysConfig();
            $lineForceClose = $sysConfig['risk_control_line_force_close']['value'];
            $lineWarning = $sysConfig['risk_control_line_warning']['value'];
            $lineOpen = $sysConfig['risk_control_line_open']['value'];

            $attr = [
                'account' => $clientSN,
                'clientSN' => $clientSN,
                'alias' => $pObj->alias,
                'password' => md5(md5($password) . $passwordSalt),
                'password_salt' => $passwordSalt,
                'create_time' => $time,
                'cellphone' => $pObj->cellphone,
                'pid' => $uidOperate,
                'level' => $levelInfo['cid'],
                'register_type' => 1,
                'uid_links' => $pObj->uid_links,
                'password_plain' => $password,
                'limit_open' => 0,
                'line_open' => $lineOpen,
                'line_warning' => $lineWarning,
                'line_force_close' => $lineForceClose,
                'is_overnight' => 1,
                // 'version' => 2,//返佣账户默认软件版本为标准版
                'template_id' => 0,
            ];

            $sql = "SELECT `uid`,`level` FROM `user` WHERE `uid` IN (" . $pObj->uid_links . ")";
            $tmp = User::findBySql($sql)->orderBy('level asc')->all();
            foreach ($tmp as $v) {
                $attr['uid_level_' . $v['level']] = $v['uid'];
            }

            $bool = self::addTrader($uidOperate, $uid, $attr, $time, $ip, $ua);
            if (!$bool) {
                return false;
            }

            if ($direction_links == '') {
                $direction_links .= $uidOperate;
            }
            $direction_links .= "," . $uid;

            //更新各层级代理的直属层级链
            $sql = "UPDATE 
                      `user` 
                    SET 
                      `direct_links` = '" . $direction_links . "',
                      `bind_user_trade` = " . $uid . "
                    WHERE 
                      `uid` IN (" . $direction_links . ")
            ";
            \Yii::$app->db->createCommand($sql)->execute();

            //各层级激活项目记录
            $sql = "INSERT INTO `activation_detail` (`uid`,`item_id`,`time`) VALUES ";
            $tmp = explode(',', $direction_links);
            array_pop($tmp);

            $record = [];
            foreach ($tmp as $t) {
                $record[] = "($t, 4, $time)";
            }
            $sql .= implode(',', $record);
            \Yii::$app->db->createCommand($sql)->execute();

            return true;
        }
    }

    /**
     * 激活用户
     *
     * @param $uid
     * @return bool
     */
    public static function activation($uid)
    {
        $db = \Yii::$app->db;
        $sql = "SELECT `id` FROM `activation_item` WHERE `is_must` = 1";
        $tmp = $db->createCommand($sql)->queryAll();
        $all = [];
        foreach ($tmp as $t) {
            $all[$t['id']] = $t['id'];
        }
        $sql = "SELECT `item_id` FROM `activation_detail` WHERE `uid` = $uid";
        $tmp = $db->createCommand($sql)->queryAll();
        $user = [];
        foreach ($tmp as $t) {
            $user[$t['item_id']] = $t['item_id'];
        }

        $flag = true;
        foreach ($all as $id) {
            if (!isset($user[$id])) {
                $flag = false;
            }
        }

        if (!$flag) {
            return false;
        }

        //所有必须项目都已完成，激活
        $sql = "UPDATE `user` SET `login_flag` = 1 WHERE `uid` = $uid";
        $db->createCommand($sql)->execute();

        return true;
    }

    public static function updatePassword($uid, $password)
    {
        $db = \Yii::$app->db;
        try {
            $sql = "UPDATE `user` SET `loginpsw` = :password WHERE `userID` = :uid";
            $db->createCommand($sql, [':password' => $password, ':uid' => $uid])->execute();

            //change_cache通知表
            $sql = "INSERT INTO `change_cache` (`userid`, `change_type`) values (" . $uid . ", 1)";
            $db->createCommand($sql)->execute();
            $code = 1;
            $msg = '';
        } catch (\Exception $e) {
            $code = 0;
            $msg = $e->getMessage();
        }

        return ['code' => $code ? 1 : 0, 'msg' => $msg];
    }
}




